// 引入defineStore
import { defineStore } from 'pinia'
import localCache from '@/utils/cache'
import router from '@/router'
import { mapMenusToRoutes, mapMenusToPermissions } from '@/utils/map-menus'
// import {
//   accountLoginRequest,
//   requestUserInfoById,
//   requestUserMenusByRoleId
// } from '@/service/login/login' //请求的地址

// 菜单的类型
interface menusState {}

export const useMenus = defineStore('menus', {
  actions: {
    // 登录
    accountLoginAction(payload: any) {
      // 1.实现登录逻辑
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      this.changeToken(token)
      localCache.setCache('token', token)

      // 发送初始化的请求(完整的role/department)
      dispatch('getInitialDataAction', null, { root: true })

      // 2.请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)

      // 3.请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
      const userMenus = userMenusResult.data
      commit('changeUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)

      // 4.跳到首页
      // router.push('/home')
      this.handleRedirect('/home')
    },

    // 缓存解码
    handleRedirect(defaultPath = '/home') {
      // 获取当前 URL 的查询参数
      const urlParams = new URLSearchParams(window.location.search);
      let redirect = urlParams.get('redirection');
    
      if (!redirect) {
        location.href = defaultPath;
        return;
      }
    
      // 多次解码，直到不能再解码为止
      let decoded = redirect;
      while (decodeURIComponent(decoded) !== decoded) {
        decoded = decodeURIComponent(decoded);
      }
    
      // 创建一个临时链接对象来提取路径部分
      const a = document.createElement('a');
      a.href = decoded;
      const pathOnly = a.pathname; // 只取路径部分，不带域名
    
      // 判断路径是否为 /login（支持各种编码形式）
      if (/\/login/i.test(pathOnly)) {
        // 如果最终跳转路径仍是登录页，则跳转到首页
        location.href = defaultPath;
      } else {
        // 否则跳转到原定目标
        location.href = decoded;
      }
    },

    changeToken(token: string) {
      this.token = token
    },
    // 保存用户信息
    changeUserInfo(userInfo: any) {
      this.userInfo = userInfo
    },
    // 保存用户菜单
    changeUserMenus(userMenus: any) {
      console.log(userMenus, '我是登录成功后返回用户的动态菜单')
      this.userMenus = userMenus

      console.log('注册动态路由')

      // userMenus => routes    拿到登录用户对应的菜单路由
      const routes = mapMenusToRoutes(userMenus)

      // 将routes => router.main.children
      routes.forEach((route) => {
        router.addRoute('main', route) //main后面换成layout入口
      })

      // 获取用户按钮的权限
      const permissions = mapMenusToPermissions(userMenus)
      this.permissions = permissions
    }
    // 退出登录
    logout(){
      router.push(`/login?redirection=${encodeURIComponent(location.href)}`)
    }
  },
  state() {
    return {
      // menus: localCache.getCache('menus', true) || [],
      userMenus: [
        {
          id: '1b8651cd-2a22-4202-a236-01747a2ff404',
          parentId: '0',
          children: [
            {
              id: '02ddeeb8-a496-4200-9d9e-233b0012b2f5',
              parentId: '1b8651cd-2a22-4202-a236-01747a2ff404',
              children: null,
              name: '统计报表',
              code: '20241205071244030033',
              status: 1,
              type: 0,
              level: 2,
              appId: 'a56fb332-fd68-4be2-acd7-e2ea9f7aac76',
              appName: '标注系统',
              dimId: '',
              dimName: null,
              urlType: 0,
              url: '/statist',
              sort: null,
              remark: '',
              createTime: '2024-12-05 15:12:45',
              updateTime: '2024-12-05 15:14:13',
              ico: ''
            },
            {
              id: 'aede768a-ec43-4b32-8c88-26790ff24f93',
              parentId: '1b8651cd-2a22-4202-a236-01747a2ff404',
              children: null,
              name: '任务管理',
              code: '20241205031700030011',
              status: 1,
              type: 0,
              level: 2,
              appId: 'a56fb332-fd68-4be2-acd7-e2ea9f7aac76',
              appName: '标注系统',
              dimId: '',
              dimName: null,
              urlType: 0,
              url: '/task',
              sort: null,
              remark: '',
              createTime: '2024-12-05 11:17:01',
              updateTime: '2024-12-05 11:28:19',
              ico: ''
            },
            {
              id: '4757935b-1c13-494b-8994-23348b028233',
              parentId: '1b8651cd-2a22-4202-a236-01747a2ff404',
              children: [
                {
                  id: '69a7aaa9-23f4-425a-86fe-50337a3330e3',
                  parentId: '4757935b-1c13-494b-8994-23348b028233',
                  children: null,
                  name: '公会成员管理',
                  code: '20241217013355030037',
                  status: 1,
                  type: 0,
                  level: 3,
                  appId: 'a56fb332-fd68-4be2-acd7-e2ea9f7aac76',
                  appName: '标注系统',
                  dimId: '',
                  dimName: null,
                  urlType: 0,
                  url: '/guildMembers',
                  sort: null,
                  remark: '',
                  createTime: '2024-12-17 09:33:56',
                  updateTime: '2024-12-17 09:35:38',
                  ico: ''
                }
              ],
              name: '公会管理',
              code: '20241205031734030012',
              status: 1,
              type: 0,
              level: 2,
              appId: 'a56fb332-fd68-4be2-acd7-e2ea9f7aac76',
              appName: '标注系统',
              dimId: '',
              dimName: null,
              urlType: 0,
              url: '/guild',
              sort: null,
              remark: '',
              createTime: '2024-12-05 11:17:34',
              updateTime: '2024-12-05 11:27:53',
              ico: ''
            }
          ],
          name: '标注系统',
          code: '20241205031630030010',
          status: 1,
          type: 0,
          level: 1,
          appId: 'a56fb332-fd68-4be2-acd7-e2ea9f7aac76',
          appName: '标注系统',
          dimId: null,
          dimName: null,
          urlType: 0,
          url: null,
          sort: null,
          remark: null,
          createTime: '2024-12-05 11:16:31',
          updateTime: '2024-12-05 11:16:31',
          ico: null
        }
      ],
      token: '',
      userInfo: {},
      permissions: [] //按钮全权限
    }
  },
  getters: {
    menus: (state) => state.menus,
    token: (state) => state.token,
    userInfo: (state) => state.userInfo
  }
})
